from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from pydantic import BaseModel, EmailStr, Field
from typing import Optional
from datetime import datetime

from core.database import Base

# 数据库模型 - 用户表
class User(Base):
    """用户模型类"""
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True, comment="用户ID")
    username = Column(String(50), unique=True, index=True, nullable=False, comment="用户名")
    email = Column(String(100), unique=True, index=True, nullable=False, comment="邮箱")
    password_hash = Column(String(255), nullable=False, comment="密码哈希")
    avatar_url = Column(String(255), nullable=True, comment="头像URL")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    last_login_at = Column(DateTime, nullable=True, comment="最后登录时间")

# Pydantic 数据模型
class BaseUserModel(BaseModel):
    """用户基础数据模型"""
    class Config:
        orm_mode = True

class UserCreate(BaseUserModel):
    """用户注册请求模型"""
    username: str = Field(..., min_length=3, max_length=50)
    email: EmailStr = Field(..., max_length=100)
    password: str = Field(..., min_length=8, max_length=20)

class UserLogin(BaseUserModel):
    """用户登录请求模型"""
    email: EmailStr
    password: str

class UserProfile(BaseUserModel):
    """用户资料响应模型"""
    id: int
    username: str
    email: str
    avatar_url: Optional[str] = None
    is_active: bool
    created_at: datetime
    updated_at: datetime

class UserResponse(BaseUserModel):
    """用户响应模型"""
    id: int
    username: str
    email: str

class UserUpdate(BaseUserModel):
    """用户更新请求模型"""
    username: Optional[str] = Field(None, min_length=3, max_length=50)
    email: Optional[EmailStr] = Field(None, max_length=100)
    password: Optional[str] = Field(None, min_length=8, max_length=20)
    avatar_url: Optional[str] = Field(None, max_length=255)

# 认证令牌模型
class Token(BaseUserModel):
    """认证令牌响应模型"""
    access_token: str
    token_type: str = "bearer"
    user: UserProfile